package com.data_structure_algorithm.data_structure.stack.operationstack;


import com.data_structure_algorithm.data_structure.stack.StackArray;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc 栈实现字符串表达式运算
 */
public class StackOperation {

  public static void main(String[] args) {
    StackArray stackNum = new StackArray(10);
    StackArray stackOper = new StackArray(10);

    String expression = "            300 + 2 * 6 - 200";
    expression = expression.replace(" ", "");

    String var = "";//用于拼接多位数

    char[] chars = expression.toCharArray();

    for (int i = 0; i < chars.length; i++) {
      //如果是数字，入数栈
      //如果是符号，判断优先级
      if (stackOper.isOper(chars[i])) {
        //符号
        //如果栈空，直接入栈
        if (stackOper.top == -1) {
          stackOper.push(chars[i]);
          continue;
        }

        if (stackOper.top != -1) {
          //如果栈不空，比较大小
          //如果当前大，入栈
          int pop = stackOper.peek();
          //判断优先级
          int oldOper = stackOper.priority(pop);

          int curOper = stackOper.priority(chars[i]);

          //当前符号大于栈内首个符号，直接入栈
          if (oldOper < curOper) {
            stackOper.push(chars[i]);
          } else {
            //小于，弹出两个数

            int cal = stackOper.cal(stackNum.pop(), stackNum.pop(), stackOper.pop());
            //运算后压数栈，当前符号入符号栈
            stackNum.push(cal);
            stackOper.push(chars[i]);
          }
        }


      } else {
        //多字符追加 如 ‘2’，‘0’，‘0’ ---> 200
        var+=(chars[i]);

        //如果是最后一位直接进栈
        if (i == chars.length - 1) {
          stackNum.push(Integer.parseInt(var));
          break;
        }



        //问题：如果是数字，再往后看一位
        //数字
        i++;

        boolean oper = stackNum.isOper(chars[i]);

        i--;


        if(oper){

          stackNum.push(Integer.parseInt(var));
          var="";
        }


      }
    }
    System.out.println("----");

    //获取结果
    //如果符号栈为空，说明结束
    while (true) {
      if (stackOper.top == -1) {
        break;
      }
      int v1 = stackNum.pop();
      int v2 = stackNum.pop();
      int oper = stackOper.pop();
      int cal = stackNum.cal(v1, v2, oper);
      stackNum.push(cal);


    }

    System.out.println(stackNum.pop());
  }



}


